package com.sne.airways.basecore.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


/**
 * Created by IntelliJ IDEA.
 * User: 卞京帅 {bjslogin#gmail.com}
 * Date: 12-11-11
 * Time: 上午9:18
 * 时光太匆匆,,,
 */
public class CommonUtils {
    protected CommonUtils(){
    }

    private static ThreadLocal<HttpServletRequest> requestThreadLocal = new ThreadLocal<HttpServletRequest>();
    private static ThreadLocal<HttpServletResponse> responseThreadLocal = new ThreadLocal<HttpServletResponse>();
    private static ThreadLocal<ServletContext> servletContextThreadLocal = new ThreadLocal<ServletContext>();
    private static ApplicationContext ctx = null;

    public static void setRequest(HttpServletRequest request){
        requestThreadLocal.set(request);
    }

    public static void setResponse(HttpServletResponse response){
        responseThreadLocal.set(response);
    }

    public static void setServletContext(ServletContext context){
        servletContextThreadLocal.set(context);
    }

    public static void removeCommon(){
        requestThreadLocal.remove();
        responseThreadLocal.remove();
        servletContextThreadLocal.remove();
    }

    /**
     * 获取request
     * @return HttpRequest
     */
    public static HttpServletRequest getRequest() {
        return requestThreadLocal.get();
    }

    /**
     * 获取response
     * @return HttpResponse
     */
    public static HttpServletResponse getResponse() {
        return responseThreadLocal.get();
    }

    /**
     * 获取session
     * @return HttpSession
     */
    public static HttpSession getHttpSession() {
        return requestThreadLocal.get().getSession();
    }

    /**
     * 向session中
     * @param key
     * @param value
     */
    public static void setSessionAttribute(String key,Object value){
        requestThreadLocal.get().getSession().setAttribute(key,value);
    }

    /**
     * 获取spring bean的静态方法
     * @param clazz Class
     * @return object bean
     */
    public static <T> T getBean(Class<T> clazz){
        if(ctx == null){
            ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContextThreadLocal.get());
        }
        return ctx.getBean(clazz);
    }

    /**
     * 获取一个32位长度不会重复的uuid
     * @return uuid
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}
